/**
 * 
 */
package wayic.utunes.lyrics;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.webharvest.runtime.variables.Variable;

import wayic.http.Content;
import wayic.http.HttpFactory;
import wayic.http.extract.Harvester;
import wayic.http.extract.HostNotConfiguredEx;
import wayic.search.Hit;
import wayic.search.Result;
import wayic.utils.SearchUtils;
import wayic.utunes.events.AsynchTrackAdapter;
import wayic.utunes.events.TrackEvent;

/**
 * @author ashesh . nishant @ gmail . com
 * 
 */
public class LyricsSearcher extends AsynchTrackAdapter {

    private static Logger LOGGER = Logger.getLogger(LyricsSearcher.class);

    /**
     * track started
     */
    public void trackStarted(TrackEvent tEvent) {
        LyricsQuery query = new LyricsQuery(tEvent.getTrack());
        Result result = query.search();
        Set<Hit> hits = result.getHits();
        if (hits.size() > 0) {
            for (Hit hit : hits) {
                String extract = "";
                try {
                    extract = Harvester.instance().extract(hit.getUrl());
                    
                } catch (HostNotConfiguredEx e) {
                    LOGGER.warn(e.getMessage());
                }
                if(extract == null || extract.trim().equals("")){
                    Content content = HttpFactory.load(hit.getUrl());
                    if(content == null || content.getHTTPStatusCode() != HttpStatus.SC_OK){
                        LOGGER.info("Ignoring : " + hit.getUrl());
                        continue;
                    }
                    extract = new TestSiteExtractor().extract(content.getContent());
                }
//                String rawContent = webFetch(hit.getUrl());
                LOGGER.info("------------------------------------------------");
                LOGGER.info("Thanks to " + SearchUtils.friendlyName(hit.getUrl().getHost()));
                LOGGER.info(hit.getUrl());
                LOGGER.info("------------------------------------------------");
                LOGGER.info(extract);
                break;
            }
        }

    }

    protected String webFetch(URL url) {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter("http.protocol.allow-circular-redirects", new Boolean(true));
        HttpMethod method = new GetMethod(url.toExternalForm());
        method.setFollowRedirects(true);
        try {
            // Execute the method.
            int statusCode = httpClient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                LOGGER.error("Method failed: " + method.getStatusLine());
            }
            byte[] responseBody = method.getResponseBody();
            String response = new String(responseBody);
            return response;

        } catch (HttpException e) {
            LOGGER.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            LOGGER.error("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return null;
    }

}
